<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Tags;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class TagsController extends Controller
{
    protected $keys = [
        'cache:tags',
    ];

    protected function clear()
    {
        foreach ($this->keys as $key) {
            Cache::forget($key);
        }
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $lang = request()->input('lang');
        $items = Tags::when($lang, function ($query, $lang) {
            $query->where('lang', $lang);
        })->get();
        return $this->successful($items);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $info = Tags::where('title', $request->post('title'))->exists();
        if ($info) {
            return $this->successful();
        }
        $this->clear();
        return $this->successful(Tags::create($request->all()));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Tags  $tag
     * @return \Illuminate\Http\Response
     */
    public function show(Tags $tag)
    {
        return $this->successful($tag);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  \App\Models\Tags  $productparam
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Tags $tag)
    {
        $tag->update($request->all());
        $this->clear();

        return $this->successful($tag);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Tags  $tag
     * @return \Illuminate\Http\Response
     */
    public function destroy(Tags $tag)
    {
        $tag->delete();
        $this->clear();
        return $this->successful([], '删除成功');
    }

    public function batchDelete()
    {
        $ids = request()->post('id');
        if ($ids) {
            Tags::destroy($ids);
        }
        return $this->successful($ids, '删除成功');
    }
}
